package com.zy.control;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zy.entity.Course;
import com.zy.entity.Subject;
import com.zy.entity.User;
import com.zy.entity.Video;
import com.zy.service.UserService;
import com.zy.util.ImageCut;
import com.zy.util.MD5Util;
import com.zy.util.javaEmailUtil;

@Controller
@Component
@RequestMapping("/user")
public class UserControl {//本类中方法倒序
	
	@Autowired
	private UserService us;
	public UserService getUs() {
		return us;
	}
	public void setUs(UserService us) {
		this.us = us;
	}
	//去section页面播放视频
	@RequestMapping("/showVideo")
	public ModelAndView showVideo(Video v,String subject_name){
		ModelAndView mv=new ModelAndView();
		System.out.println(subject_name);
		Video video = us.selectVideoById(v);
		//c.setId(video.getCourse_id());
		//Course selectCourseById = us.selectCourseById(c);
		
		mv.addObject("video", video);
		mv.addObject("subject_name", subject_name);
		return mv;
	}
	//course页面
		@RequestMapping("/course")
		public ModelAndView course(Subject sb,Video v){
			ModelAndView mv=new ModelAndView();
			System.out.println(sb.getId()+"*********************");
			Subject subject = us.selectSubjectById(sb);
			for(Course c:subject.getClist()){
				for(Video vd:c.getVlist()){
					vd.setTime(formatTime(Integer.parseInt(vd.getTime())));
				}
			}
			
			mv.addObject("subject", subject);
			mv.setViewName("/WEB-INF/before/course.jsp");
			return mv;
		}
	public String formatTime(int time){
		String str=time+"秒";
		if(time>60){
			int ss=time%60;
			int mm=time/60;
			str=mm+":"+ss;
			if(mm>60){
				mm=mm%60;
				int hh=mm/60;
				str=hh+":"+str;
			}
		}
		return str;
	}
	//去course页面
		@RequestMapping("/toCourse")
		public ModelAndView toCourse(){
			ModelAndView mv=new ModelAndView();
			mv.setViewName("/WEB-INF/before/course.jsp");
			return mv;
		}
	//去section页面
		@RequestMapping("/toSection")
		public ModelAndView toSection(){
			ModelAndView mv=new ModelAndView();
			mv.setViewName("/WEB-INF/before/course.jsp");
			return mv;
		}
	//重置密码
	@RequestMapping("/resetPassword")
	public ModelAndView resetPassword(User u,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		
		u.setPassword(MD5Util.getMd5plus(u.getPassword()));
		User ur = (User)request.getSession().getAttribute("user");
		u.setEmail(ur.getEmail());
		request.getSession().setAttribute("user", u);
		//System.out.println("++++++++++++++++++++++++++"+u.getPassword());
		//System.out.println("*-----------------------------------*"+u.getEmail());
		us.updatePasswordByEmail(u);
		User user = us.selectUserByEmail(ur);
		request.getSession().setAttribute("user", user);
		mv.setViewName("/WEB-INF/before/my_profile.jsp");
		return mv;
	}
	//去重置密码
	@RequestMapping("/validateEmailCode")
	public ModelAndView validateEmailCode(User u,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		
		request.getSession().setAttribute("user", u);
		//System.out.println("*+++++++++++++++++++++++++*"+u.getEmail());
		String yzm = javaEmailUtil.getYzm();
		if(u.getCode().equals(yzm)){
			mv.setViewName("/WEB-INF/before/reset_password.jsp");
		}else{
			mv.setViewName("redirect:/user/forgetPassword.action");
		}
		
		return mv;
	}
	//发送验证码
	@RequestMapping("/sendEmail")
	@ResponseBody
	public Object sendEmail(User u) throws Exception{
		List<User> allEmail = us.selectAllEmail();
		for (User user : allEmail) {
			if(u.getEmail().trim().equals(user.getEmail())){
				javaEmailUtil.sendEmail(u.getEmail());
				return "success";
			}
		}
		return "false";
	}
	//去忘记密码
	@RequestMapping("/forgetPassword")
	public ModelAndView forgetPassword(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/WEB-INF/before/forget_password.jsp");
		return mv;
	}
	//验证邮箱
	@RequestMapping("/yzEmail")
	@ResponseBody
	public Object yzEmail(User u){
		//System.out.println("5555");
		List<User> elist = us.selectAllEmail();
		for (User user : elist) {
			if(u.getEmail().equals(user.getEmail())){
				return "success";
			}
		}
		return "fghjk";
	}
	//注册
	@RequestMapping("/insertUser")
	public ModelAndView insertUser(User u,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		String md5 = MD5Util.getMd5plus(u.getPassword());
		u.setPassword(md5);
		us.insertUser(u);
		User user = us.selectUserById(u);
		request.getSession().setAttribute("user", user);
		mv.setViewName("/WEB-INF/before/my_profile.jsp");
		return mv;
	}
	//验证旧密码
	@RequestMapping("/validatePassword")
	@ResponseBody
	public Object validatePassword(String password,HttpServletRequest request){
		User user = (User)request.getSession().getAttribute("user");
		if(MD5Util.getMd5plus(password.trim()).equals(user.getPassword())){
			return "success";
		}else{
			return "ghj";
		}
	}
	//去密码安全
	@RequestMapping("/passwordSafe")
	public ModelAndView passwordSafe(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/WEB-INF/before/password_safe.jsp");
		return mv;
	}
	//修改密码
	@RequestMapping("/updatePassword")
	public ModelAndView updatePassword(User u,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		u.setPassword(MD5Util.getMd5plus(u.getPassword()));
		//System.out.println(u.getId()+"----"+u.getPassword());
		us.updatePassword(u);
		mv.setViewName("redirect:/user/showMyProfile.action");
		return mv;
	}
	//去更改头像
	@RequestMapping("/changeAvatar")
	public ModelAndView changeAvatar(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/WEB-INF/before/change_avatar.jsp");
		return mv;
	}
	//更改头像
	@RequestMapping("/upLoadImage")
	public ModelAndView upLoadImage(User u,MultipartFile imgFile,HttpServletRequest request) throws IOException{
		//在方法中获取坐标
		float x1 = 0,x2=0,y1=0,y2=0,width=0;
		boolean isCut =false;
		if(null!=request.getParameter("x1")&&!"".equals(request.getParameter("x1"))){
			x1= Float.parseFloat(request.getParameter("x1"));
			y1= Float.parseFloat(request.getParameter("y1"));
			x2= Float.parseFloat(request.getParameter("x2"));
			y2= Float.parseFloat(request.getParameter("y2"));
			width= x2-x1;
			isCut=true;
		}
		//上传图片
		ModelAndView mv=new ModelAndView();
		System.out.println(u.getId());
		InputStream is = imgFile.getInputStream();
		String realPath = getRealPath(request);
		String newName = getNewName(imgFile);
		OutputStream os=new FileOutputStream(realPath+"\\"+newName);
		IOUtils.copy(is, os);
		is.close();
		os.close();
		//裁剪图片
		if(isCut){
			  
		    ImageCut.cutImage(realPath+"\\"+newName, (int)x1, (int)y1, (int)width, (int)width);
		}
		u.setImgUrl("headImg/"+newName);
		us.upLoadImage(u);
		
		/*User user = us.selectUserById(u);
		request.getSession().setAttribute("user", user);
		mv.addObject("user", user);*/
		mv.setViewName("redirect:/user/showMyProfile.action");
		return mv;
	}
	//获得新名字
	public String getNewName(MultipartFile imgFile){
		UUID randomUUID = UUID.randomUUID();
		String originalFilename = imgFile.getOriginalFilename();
		String extension = FilenameUtils.getExtension(originalFilename);
		String newName=randomUUID+"."+extension;
		return newName;
	}
	//获得真实路径
	public String getRealPath(HttpServletRequest request){
		String path="/headImg";
		String realPath = request.getServletContext().getRealPath(path);
		File fi=new File(realPath);
		if(!fi.exists()){
			fi.mkdirs();
		}
		return realPath;
	}
	//去个人中心
	@RequestMapping("/showMyProfile")
	public ModelAndView showMyProfile(User u,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		u = (User)request.getSession().getAttribute("user");
		
		User user = us.selectUserById(u);
		request.getSession().setAttribute("user", user);
		mv.addObject("user", user);
		mv.setViewName("/WEB-INF/before/my_profile.jsp");
		return mv;
	}
	//去更改资料
	@RequestMapping("/changeProfile")
	public ModelAndView changeProfile(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/WEB-INF/before/change_profile.jsp");
		return mv;
	}
	//更改资料
	@RequestMapping("/updateUser")
	public ModelAndView updateUser(User u,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		us.updateUser(u);
		User user = us.selectUserById(u);
		request.getSession().setAttribute("user", user);
		mv.addObject("user", user);
		mv.setViewName("/WEB-INF/before/my_profile.jsp");
		return mv;
	}
	//去首页
	@RequestMapping("/toIndex")
	public ModelAndView toIndex(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/index.jsp");
		return mv;
	}
	//登录
	@RequestMapping("/login")
	public ModelAndView login(User u,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		u.setPassword(MD5Util.getMd5plus(u.getPassword()));
		if(us.login(u,request)){
			User user = (User)request.getSession().getAttribute("user");
			
			mv.addObject("user", user);
			mv.setViewName("/WEB-INF/before/my_profile.jsp");
			return mv;
		}else{
			mv.setViewName("/index.jsp");
			return mv;
		}
	}
	//退出
	@RequestMapping("/loginOut2")
	public ModelAndView logOut(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		HttpSession session = request.getSession(false);
		if(session==null){
			mv.setViewName("redirect:/index.jsp");
			return mv;
		}
		session.removeAttribute("user");
		mv.setViewName("redirect:/index.jsp");
		return mv;
	}
	
}
